﻿#include "MyHashTable.h"

Pair::Pair(int _key, std::string _value) :key(_key), value(_value) {

}

ArrayHashMap::ArrayHashMap() {
	//初始化数组100个
	buckets = std::vector<Pair*>(100);
}
ArrayHashMap::~ArrayHashMap() {
	for (const auto& bucket : buckets)
		delete bucket;
	buckets.clear();
}
int ArrayHashMap::hashMethod(int key) {
	int index = key % 100;
	return index;
}
//查询
std::string ArrayHashMap::get(int key) {
	int index = hashMethod(key);
	Pair* pair = buckets[index];
	if (pair == nullptr)
		return "";
	return pair->value;
}
//新增
void ArrayHashMap::add(int key, std::string value) {
	Pair* pair = new Pair(key, value);
	int index = hashMethod(key);
	buckets[index] = pair;
}
//删除
void ArrayHashMap::remove(int key) {
	int index = hashMethod(key);
	delete buckets[index];
	buckets[index] = nullptr;
}
//获取所有值
std::vector<std::string> ArrayHashMap::valueGet() {
	std::vector<std::string> valueContainer;
	for (Pair* pair : buckets) {
		if (pair != nullptr)
			valueContainer.push_back(pair->value);
	}
	return valueContainer;
}
//获取所有键
std::vector<int> ArrayHashMap::keyGet() {
	std::vector<int> keyContainer;
	for (Pair* pair : buckets) {
		if (pair != nullptr)
			keyContainer.push_back(pair->key);
	}
	return keyContainer;
}
//获取所有键值对
std::vector<Pair*> ArrayHashMap::pairGet() {
	std::vector<Pair*> pairContainer;
	for (Pair* pair : buckets) {
		if (pair != nullptr)
			pairContainer.push_back(pair);
	}
	return pairContainer;
}


void ArrayHashMap::print() {
	std::vector<Pair*> pairContainer = pairGet();
	for (auto kv : pairContainer) {
		std::cout << "key:" << kv->key << ",value:" << std::endl;
	}
}
